<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path:'/blank' }"><i class="el-icon-edit"></i>考试管理</el-breadcrumb-item>
      <el-breadcrumb-item>考试管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <el-row style="text-align: left">
      <!--    examTypeArr-->
      <el-select v-model="selectExam.type" :value="selectExam.type" placeholder="考试类型" style="width: 180px" clearable
                 @visible-change="getExamArr">
        <el-option v-for="item in examTypeArr" :label="item.content" :value="item.type" :key="item.type"></el-option>
      </el-select>
      <el-select v-if="localUser.roleId!=3" v-model="selectExam.majorId" :value="selectExam.majorId" placeholder="专业"
                 style="width: 180px;margin: 0 5px" clearable @visible-change="getExamArr">
        <el-option v-for="item in majorArr" :label="item.majorName" :value="item.id" :key="item.id"></el-option>
      </el-select>
      <el-date-picker style="width: 180px" v-model="selectExam.starTimeStr" type="datetime"
                      placeholder="选择考试开始时间"></el-date-picker>
      <el-date-picker style="width: 180px;margin: 0 5px" v-model="selectExam.endTimeStr" type="datetime"
                      placeholder="选择考试结束时间"></el-date-picker>
      <el-input style="width: 180px;" placeholder="考试名称" prefix-icon="el-icon-search"
                v-model="selectExam.examName"></el-input>
      <el-button type="success" size="medium" @click="getExamArr()" icon="el-icon-search" style="margin: 0 10px">查询
      </el-button>
      <el-button type="success" size="medium" icon="el-icon-refresh" @click="LoadUserList">刷新</el-button>
    </el-row>
    <el-row style="float: left;margin: 10px 0">
      <el-button type="primary" size="medium" icon="el-icon-plus" @click="goExamAdd">添加考试</el-button>
    </el-row>

    <!--  <div style="text-align: left">
        <el-button style="margin: 0 2px" type="danger" plain @click="openDeleteByIds()">批量删除</el-button>
      </div>-->
    <div>
      <el-table ref="multipleTable" :data="examArr" :border="true" tooltip-effect="dark" style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="考试名" prop="examName" show-overflow-tooltip header-align="center">
          <template slot-scope="scope">
            <a style="text-decoration: none;color: #409EFF;cursor:pointer"
               @click="goQuestionList(scope.row)">{{ scope.row.examName }}</a>
          </template>
        </el-table-column>
        <el-table-column label="考试类型" prop="type" show-overflow-tooltip width="120px" align="center">
          <template slot-scope="scope">
            {{ scope.row.type == 1 ? '完全公开' : '需要密码' }}
          </template>
        </el-table-column>
        <el-table-column label="考试时间" prop="starTime" show-overflow-tooltip width="180px" align="center">
          <template slot-scope="scope">
            {{ scope.row.starTime }}~{{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column
            label="专业名" prop="majorName" show-overflow-tooltip width="120px" align="center">
        </el-table-column>
        <el-table-column
            label="班级名" prop="classNames" show-overflow-tooltip width="120px" align="center">
        </el-table-column>
        <el-table-column
            label="总分" prop="totalScore" show-overflow-tooltip width="80px" align="center">
        </el-table-column>
        <el-table-column
            label="及格分" prop="passScore" show-overflow-tooltip width="80px" align="center">
        </el-table-column>
        <el-table-column
            label="创建人" prop="trueName" show-overflow-tooltip width="120px" align="center">
        </el-table-column>

        <el-table-column label="是否禁用" prop="status" width="80px" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" @change="openUpdateExamStatus(scope.row)"
                       active-value="0" inactive-value="1" active-color="#13ce66">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" header-align="center" align="center" width="100">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" circle
                       @click="getStandardExam(scope.row)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" circle
                       @click="openDeleteExam(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="text-align: right;margin: 10px auto">
      <el-pagination
          layout="total,prev, pager, next"
          @current-change="changePage"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize">
      </el-pagination>
    </div>

    <el-dialog title="修改考试基础信息" :visible.sync="examUpdateDialog">
      <el-form :model="examStandard" :rules="rules" ref="examStandard" label-width="120px" class="demo-ruleForm"
               style="text-align: left">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="examStandard.examName"></el-input>
        </el-form-item>
        <el-form-item label="考试描述" prop="examDesc">
          <el-input v-model="examStandard.examDesc"></el-input>
        </el-form-item>
        <el-form-item label="需要密码">
          <el-switch
              v-model="examStandard.type"
              active-value="2"
              inactive-value="1"
              active-color="#13ce66">
          </el-switch>
        </el-form-item>
        <el-form-item v-show="examStandard.type=='2'" label="密码">
          <el-input v-model="examStandard.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input-number v-model="examStandard.totalScore" label="总分" :disabled="true"></el-input-number>
        </el-form-item>
        <el-form-item label="及格分数" prop="passScore">
          <el-input-number v-model="examStandard.passScore" :max="examStandard.totalScore" label="及格分" :precision="0"
                           :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="考试时常(分)" prop="duration">
          <el-input-number v-model="examStandard.duration" :max="240" label="考试时常" :precision="0"
                           :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="考试开始时间">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="examStandard.starTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="考试结束时间">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="examStandard.endTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="请选择专业" prop="majorId">
          <span v-show="updateMajorDialog==false">{{ examStandard.majorName }}</span>
          <el-select v-show="updateMajorDialog"
                     v-model="examStandard.majorId"
                     :value="examStandard.majorId"
                     placeholder="专业"
                     style="width: 150px"
                     @change="getClassArr">
            <el-option v-for="item in majorArr" :label="item.majorName" :value="item.id" :key="item.id"></el-option>
          </el-select>
          <el-button type="success" size="mini" style="margin-left: 20px" @click="updateMajorDialog=true">修改</el-button>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <span v-show="updateMajorDialog==false" v-for="item in examStandard.classNames.split(',')"
                :key="item">{{ item }} </span>
          <el-select
              v-show="updateMajorDialog"
              v-model="classValue"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="班级" style="width: 150px">
            <el-option v-for="item in classArr" :label="item.className" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="examUpdateDialog = false">取 消</el-button>
          <el-button type="primary" @click="openUpdateExam">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      selectExam: {
        type: '',
        starTimeStr: '',
        endTimeStr: '',
        majorId: '',
        examName: '',
        className:''
      },
      //分页器相关数据
      total: 0,
      currentPage: 0,
      pageSize: 0,
      //由于考试就两种类型，所以直接在前端写成数组形式
      examTypeArr: [
        {
          type: '1',
          content: '完全开放'
        },
        {
          type: '2',
          content: '需要密码'
        }
      ],
      examStandard: {
        classNames: '',
      },
      classValue: [],
      //显示修改基本信息框的参数信息
      examUpdateDialog: false,
      updateMajorDialog: false,
      majorArr: [],
      classArr: [],
      examArr: [],
      localUser:{},
      multipleSelection: [],
      rules: {
        examName: [
          {required: true, message: '请输入考试名称', trigger: 'blur'}
        ],
        examDesc: [
          {required: true, message: '请输入考试介绍', trigger: 'blur'}
        ],
        date1: [
          {type: 'date', required: true, message: '请选择日期', trigger: 'blur'}
        ],
        totalScore: [
          {required: true, message: '您缺少总分', trigger: 'blur'}
        ],
        passScore: [
          {required: true, message: '请输入及格分数', trigger: 'blur'}
        ],
        duration: [
          {required: true, message: '请输入考试时常', trigger: 'blur'}
        ],
        majorId: [
          {required: true, message: '请输入专业id', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    goQuestionList(exam) {
      let url = '/exam/questionList?examId=' + exam.id;
      this.$router.push(url);
    },
    changePage(value) {
      this.$router.replace("?page=" + value);
      this.getExamArr();
    },
    openDeleteByIds() {
      this.$confirm('是否删除考试?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteByIds()
      }).catch(() => {
      });
    },
    deleteByIds() {
      let url = "http://localhost:9283/exam/deleteByIds";
      let jwt = localStorage.getItem("localJwt");
      let ids = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        ids[i] = this.multipleSelection[i].id;
      }
      this.axios
          .create({
            'headers': {
              'Authorization': jwt
            }
          }).post(url, ids).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.getExamArr();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else if (response.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.getExamArr();
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    //删除考试
    openDeleteExam(exam) {
      this.$confirm('是否删除考试?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteExam(exam)
      }).catch(() => {
      });
    },
    deleteExam(exam) {
      let url = "http://localhost:9283/exam/deleteById/" + exam.id;
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers': {
              'Authorization': jwt
            }
          }).post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.getExamArr();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else if (response.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.getExamArr();
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    //刷新页面
    LoadUserList() {
      this.selectExam = {
        type: '',
        starTimeStr: '',
        endTimeStr: '',
        majorId: '',
        examName: ''
      };
      this.getExamArr();
    },

    //修改考试基础信息
    //1、获取想要修改的考试信息
    getStandardExam(exam) {
      let url = "http://localhost:9283/exam/getStandard/" + exam.id;
      let jwt = localStorage.getItem("localJwt");
      console.log(url);
      this.axios
          .create({
            'headers': {
              'Authorization': jwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.examStandard = jsonResult.data;
          console.log(this.examStandard)
          this.examUpdateDialog = true;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    openUpdateExam() {
      this.$confirm('是否修改考试状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateExam('examStandard')
      }).catch(() => {
      });
    },
    updateExam(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.classValue)
          //如果点击了修改后提交则需调用字符串
          if (this.updateMajorDialog) {
            this.examStandard.classIds = "";
            this.examStandard.classNames = "";
            //将选中的数组拼接成字符串
            for (let i = 0; i < this.classArr.length; i++) {
              for (let j = 0; j < this.classValue.length; j++) {
                if (this.classValue[j] == this.classArr[i].id) {
                  this.examStandard.classIds += this.classValue[j] + ",";
                  this.examStandard.classNames += this.classArr[i].className + ",";
                  continue;
                }
              }
            }
            //去除拼接的,
            this.examStandard.classIds = this.examStandard.classIds.substring(0, this.examStandard.classIds.length - 1);
            this.examStandard.classNames = this.examStandard.classNames.substring(0, this.examStandard.classNames.length - 1);

            //传递专业名称
            for (let i = 0; i < this.majorArr.length; i++) {
              if (this.examStandard.majorId == this.majorArr[i].id) {
                this.examStandard.majorName = this.majorArr[i].majorName;
                break;
              }
            }
          }

          /*const regExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/;

          if (!regExp.test(this.examStandard.starTime)) {
            let startTime = new Date(this.examStandard.starTime).getTime();
            this.examStandard.starTime = new Date(startTime).toISOString();
          }
          if (!regExp.test(this.examStandard.endTime)) {
            let endTime = new Date(this.examStandard.endTime).getTime();
            this.examStandard.endTime = new Date(endTime).toISOString();
          }*/
          //将时间对象存储

          let url = "http://localhost:9283/exam/update";
          let jwt = localStorage.getItem("localJwt");
          this.axios
              .create({
                'headers': {
                  'Authorization': jwt
                }
              })
              .post(url,this.examStandard).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.getExamArr();
              this.examUpdateDialog = false;
              this.updateMajorDialog = false;
              if (jsonResult.jwt!=null){
                localStorage.setItem("localJwt",jsonResult.jwt);
              }
            }else if(jsonResult.state==70100){
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
              this.$router.push('/')
            }  else {
              this.$alert(response.data.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });


      console.log(this.examStandard)
    },

    //修改考试状态
    openUpdateExamStatus(exam) {
      this.$confirm('是否修改考试状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateStatus(exam)
      }).catch(() => {
      });
    },
    updateStatus(exam) {
      let url = "http://localhost:9283/exam/updateStatus";
      let formDate = "id=" + exam.id + "&status=" + exam.status;
      console.log(url);
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers': {
              'Authorization': jwt
            }
          }).post(url, formDate).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          });
          this.getExamArr();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else if (response.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.getExamArr();
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.getExamArr();
        }
      })
    },
    goExamAdd() {
      console.log("准备开始跳转")
      this.$router.push('/exam/addNew1');
    },
    getMajorArr() {
      let url = "http://localhost:9281/major/list";
      let jwt = localStorage.getItem("localJwt");
      console.log(url);
      this.axios
          .create({
            'headers': {
              'Authorization': jwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.majorArr = jsonResult.data;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    getClassArr() {
      let url = "http://localhost:9281/class/list?id=" + this.examStandard.majorId;
      console.log(url);
      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.classArr = jsonResult.data;
          console.log(this.classArr)
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
          });
        }
      })
    },
    getExamArr() {
      this.localUser = JSON.parse(localStorage.getItem("localUser"));
      let page = this.$router.currentRoute.query.page;
      if (page < 1 || page == null) {
        page = 1;
      }
      console.log(this.selectExam)
      if (this.selectExam.starTimeStr != '') {
        this.selectExam.starTimeStr = new Date(this.selectExam.starTimeStr).toISOString();
      }
      if (this.selectExam.endTimeStr != '') {
        this.selectExam.endTimeStr = new Date(this.selectExam.endTimeStr).toISOString();
      }
      if(this.localUser.roleId==3){
        this.selectExam.majorId =this.localUser.majorId;
        this.selectExam.className = this.localUser.className;
      }
      console.log(this.selectExam)
      let url = "http://localhost:9283/exam/list/" + page;
      let formData = this.qs.stringify(this.selectExam);
      console.log(formData);
      url = url + "?" + formData;
      let jwt = localStorage.getItem("localJwt");
      console.log(url);
      this.axios
          .create({
            'headers': {
              'Authorization': jwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          console.log(jsonResult)
          this.examArr = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.currentPage = jsonResult.data.currentPage;
          this.pageSize = jsonResult.data.pageSize;
          console.log(this.examArr)
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  },
  mounted() {
    this.getMajorArr();
    this.getExamArr();
    //this.getClassArr();
  }
}
</script>
